package com.mo.xi.ge.info.help

import android.content.Context
import android.media.MediaDrm
import android.os.Build
import android.provider.Settings
import android.util.Base64
import com.google.gson.GsonBuilder
import com.google.gson.JsonObject
import com.mo.xi.ge.info.DaleLoca
import com.mo.xi.ge.info.DaleInfoInstance
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.Locale
import java.util.UUID


/**
 * date:2024/1/25
 **/
internal object EntryInfoManager {

    const val VERSION_STR = "1.0.6"
    const val DATA_VERSION = "24072011"
    var mSource = ""

    val NORMALUUID by lazy {
        UUID(-0x121074568629b532L, -0x5c37d8232ae2de13L)
    }

    private var mDalaData: DalaData? = null

    var mDalaDeviceId: String? = null

    @DaleLoca
    var mInfoTag: String? = null

    var mDalaDramId: String? = null
        get() {
            if (field.isNullOrEmpty()) {
                field = getDrmId()
            }
            return field
        }

    val mRequestId: String
        get() = mDalaData?.requestId.orEmpty()

    var mDataToken: String? = null
        get() = mDalaData?.dataToken.orEmpty()

    fun reCreateToken(context: Context) {
        val reqId = UUID.randomUUID().toString()
        mDalaData = DalaData(createToken(context, reqId), reqId)
    }

    private fun getDrmId(): String? {
        var mediaDrm: MediaDrm? = null
        return try {
            mediaDrm = MediaDrm(NORMALUUID)
            val wijdaiD = mediaDrm.getPropertyByteArray(MediaDrm.PROPERTY_DEVICE_UNIQUE_ID)
            Base64.encodeToString(wijdaiD, Base64.URL_SAFE).trim { it <= ' ' }
        } catch (e: Exception) {
            ""
        } finally {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && mediaDrm != null) {
                mediaDrm.close()
            } else {
                mediaDrm?.release()
            }
        }
    }

    fun generatorId(context: Context): String {
        val serialNum = try {
            Build.SERIAL
        } catch (e: Exception) {
            ""
        }
        val manufacturer = Build.MANUFACTURER
        val brand = Build.BRAND
        val board = Build.BOARD
        val device = Build.DEVICE
        val tempId =
            "1024" + serialNum.length % 20 + brand.length % 20 + manufacturer.length % 20 + board.length % 20 + device.length % 20

        var macAddress = try {
            Settings.Secure.getString(context.contentResolver, "bluetooth_address").orEmpty()
        } catch (e: java.lang.Exception) {
            ""
        }
        if (macAddress.isEmpty()) {
            macAddress = DeviceInfoUtil.getAndroidId(context)
        }
        var imei = DeviceInfoUtil.getSysImei(context)
        if (imei.isEmpty()) {
            imei = DeviceInfoUtil.getAndroidId(context)
        }
        val paramsBuilder = StringBuilder()
        paramsBuilder.append(serialNum).append(",").append(manufacturer).append(",").append(brand)
            .append(",")
            .append(board).append(",").append(device).append(",").append(macAddress).append(",")
            .append(imei)
        mDalaDeviceId = Base64Util.toBase64(paramsBuilder.toString()).uppercase()
        return convertToMd5(tempId + macAddress + imei)
    }

    private fun convertToMd5(id: String): String {
        var msgDigest: MessageDigest? = null
        try {
            msgDigest = MessageDigest.getInstance("MD5")
        } catch (var7: NoSuchAlgorithmException) {
            var7.printStackTrace()
        }
        msgDigest ?: return id
        msgDigest.update(id.toByteArray(), 0, id.length)
        val md5Data = msgDigest.digest()
        var resultId = ""
        for (i in md5Data.indices) {
            val b = 255 and md5Data[i].toInt()
            if (b <= 15) {
                resultId += "0"
            }
            resultId += Integer.toHexString(b)
        }
        return resultId.uppercase(Locale.getDefault())
    }

    private fun createToken(context: Context, reqId: String): String {
        val jobj = JsonObject()
        jobj.addProperty("RequestId", reqId)
        jobj.addProperty("MobDeviceId", generatorId(context))
        jobj.addProperty("SDKSource", mSource)
        jobj.addProperty("DataVersion", DATA_VERSION)
        jobj.addProperty("PackageName", context.packageName)
        jobj.addProperty("Partner", DataConstant.mSecretid)
        jobj.addProperty("DeviceTime", System.currentTimeMillis())
        jobj.addProperty("OSType", "Android")
        jobj.addProperty("OSVersion", Build.VERSION.SDK_INT)
        jobj.addProperty("IMEI", DeviceInfoUtil.getSysImei(context))
        jobj.addProperty("GAID", DaleInfoInstance.INSTANCE.mGaidBack?.invoke().orEmpty())
        jobj.addProperty("SdkPublicIp", DaleInfoInstance.INSTANCE.mIpAddr?.invoke().orEmpty())
        jobj.addProperty("PackageCode", context.versionCode())
        jobj.addProperty("PackageVersion", context.versionName())
        jobj.addProperty("ActionMode", mInfoTag.orEmpty())
        jobj.addProperty("DrmId", mDalaDramId)

        val jsonStr = GsonBuilder().serializeNulls().create().toJson(jobj)
//        Log.d("debug_DataOtherUtil", "generatorToken: strjson = $strJson")
        return Base64Util.toBase64(EncryptWrapper.encryptSuper(jsonStr, DataConstant.mPublicKey))
    }

    fun getDeviceNickName(context: Context): String {
        var name: String? = ""
        try {
            name = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {
                Settings.Global.getString(context.contentResolver, Settings.Global.DEVICE_NAME)
            } else {
                Settings.Global.getString(context.contentResolver, "device_name")
            }
        } catch (e: java.lang.Exception) {
        }
        return name.orEmpty()
    }
}
